package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.MonitoringEnergy;
import com.ruoyi.business.mapper.MonitoringEnergyMapper;
import com.ruoyi.business.service.IMonitoringEnergyService;
import com.ruoyi.common.utils.CommentUtil;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 能源监控Service业务层处理
 * 
 * @author qiancheng
 * @date 2025-09-01
 */
@Service
public class MonitoringEnergyServiceImpl extends ServiceImpl<MonitoringEnergyMapper, MonitoringEnergy> implements IMonitoringEnergyService
{
    @Autowired
    private MonitoringEnergyMapper monitoringEnergyMapper;

    /**
     * 查询能源监控
     * 
     * @param id 能源监控主键
     * @return 能源监控
     */
    @Override
    public MonitoringEnergy selectMonitoringEnergyById(Long id)
    {
        return monitoringEnergyMapper.selectMonitoringEnergyById(id);
    }

    /**
     * 查询能源监控列表
     * 
     * @param monitoringEnergy 能源监控
     * @return 能源监控
     */
    @Override
    public List<MonitoringEnergy> selectMonitoringEnergyList(MonitoringEnergy monitoringEnergy)
    {
        return monitoringEnergyMapper.selectMonitoringEnergyList(monitoringEnergy);
    }

    /**
     * 新增能源监控
     * 
     * @param monitoringEnergy 能源监控
     * @return 结果
     */
    @Override
    public int insertMonitoringEnergy(MonitoringEnergy monitoringEnergy)
    {
        Date now = DateUtils.getNowDate();
        monitoringEnergy.setCreateTime(now);

        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        monitoringEnergy.setRecordYear((long) cal.get(Calendar.YEAR));
        monitoringEnergy.setRecordMonth((long) (cal.get(Calendar.MONTH) + 1));
        monitoringEnergy.setRecordDay((long) cal.get(Calendar.DAY_OF_MONTH));

        // 手动生成主键
        monitoringEnergy.setId(IdWorker.getId());
        return monitoringEnergyMapper.insertMonitoringEnergy(monitoringEnergy);
    }

    /**
     * 修改能源监控
     * 
     * @param monitoringEnergy 能源监控
     * @return 结果
     */
    @Override
    public int updateMonitoringEnergy(MonitoringEnergy monitoringEnergy)
    {
        monitoringEnergy.setUpdateTime(DateUtils.getNowDate());
        return monitoringEnergyMapper.updateMonitoringEnergy(monitoringEnergy);
    }

    /**
     * 批量删除能源监控
     * 
     * @param ids 需要删除的能源监控主键
     * @return 结果
     */
    @Override
    public int deleteMonitoringEnergyByIds(Long[] ids)
    {
        return monitoringEnergyMapper.deleteMonitoringEnergyByIds(ids);
    }

    /**
     * 删除能源监控信息
     * 
     * @param id 能源监控主键
     * @return 结果
     */
    @Override
    public int deleteMonitoringEnergyById(Long id)
    {
        return monitoringEnergyMapper.deleteMonitoringEnergyById(id);
    }

    /**
     * 根据传入的小时数，获取对应时间范围内按能源类型分组的能源监控统计数据
     *
     * @param monitoringEnergy
     * @return 对应时间范围内按能源类型分组的能源监控统计数据列表
     */
    @Override
    public List<MonitoringEnergy> getEnergyDataByHours(MonitoringEnergy monitoringEnergy) {
        CommentUtil.resetCompanyIdIfNull(monitoringEnergy);
        return baseMapper.getEnergyDataByHours(monitoringEnergy);
    }

    /**
     * 根据年月获取不同能源的使用量
     *
     * @param monitoringEnergy 包含 recordYear、recordMonth
     * @return 按能源分组的使用量列表
     */
    @Override
    public List<MonitoringEnergy> getUsageByMonth(MonitoringEnergy monitoringEnergy) {
        List<MonitoringEnergy> usageByMonth = monitoringEnergyMapper.getUsageByMonth(monitoringEnergy);

        // 按energy_name分组，汇总energyUsage，小于0则返回0
        Map<String, BigDecimal> groupedResult = usageByMonth.stream()
                .collect(Collectors.groupingBy(
                        MonitoringEnergy::getEnergyName,
                        Collectors.reducing(
                                BigDecimal.ZERO,
                                energy -> energy.getEnergyUsage() != null ? energy.getEnergyUsage() : BigDecimal.ZERO,
                                (sum, usage) -> {
                                    BigDecimal total = sum.add(usage);
                                    return total.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : total;
                                }
                        )
                ));

        // 将Map转换为List<MonitoringEnergy>
        return groupedResult.entrySet().stream()
                .map(entry -> {
                    MonitoringEnergy energy = new MonitoringEnergy();
                    energy.setEnergyName(entry.getKey());
                    energy.setEnergyUsage(entry.getValue());
                    // 保留原有的年份和月份信息
                    energy.setRecordYear(monitoringEnergy.getRecordYear());
                    energy.setRecordMonth(monitoringEnergy.getRecordMonth());
                    return energy;
                })
                .collect(Collectors.toList());
    }

//    /**
//     * 根据年月查询各能源类型每天的能源使用数据
//     * @param monitoringEnergy
//     * @return
//     */
//    @Override
//    public MultiLineChartDataVo getDailyUsageByMonth(MonitoringEnergy monitoringEnergy) {
//        CommentUtil.resetCompanyIdIfNull(monitoringEnergy);
//        List<MonitoringEnergy> resultList = monitoringEnergyMapper.getDailyUsageByMonth(monitoringEnergy);
//        // 提取所有日期并排序
//        List<Long> xAxis = resultList.stream()
//                .map(MonitoringEnergy::getRecordDay)
//                .distinct()
//                .sorted()
//                .collect(Collectors.toList());
//
//        // 按能源名称分组并处理数据
//        List<SeriesDataVo> yAxis = resultList.stream()
//                .collect(Collectors.groupingBy(MonitoringEnergy::getEnergyName))
//                .entrySet().stream()
//                .map(entry -> {
//                    String energyName = entry.getKey();
//                    List<MonitoringEnergy> dailyUsages = entry.getValue();
//                    ArrayList<Double> data = new ArrayList<>(Collections.nCopies(xAxis.size(), 0.0));
//                    dailyUsages.forEach(usage -> {
//                        int index = xAxis.indexOf(usage.getRecordDay());
//                        if (index != -1) {
//                            data.set(index, usage.getEnergyUsage() != null ? usage.getEnergyUsage().doubleValue() : 0.0);
//                        }
//                    });
//                    SeriesDataVo seriesData = new SeriesDataVo();
//                    seriesData.setName(energyName);
//                    seriesData.setData(data);
//                    return seriesData;
//                })
//                .collect(Collectors.toList());
//
//        MultiLineChartDataVo multiLineChartData = new MultiLineChartDataVo();
//        multiLineChartData.setXAxis(xAxis);
//        multiLineChartData.setYAxis(yAxis);
//        return multiLineChartData;
//    }
//
//    /**
//     * 根据年月能源名称获取产品各规格每天的能耗趋势原始数据
//     * @param monitoringEnergy
//     * @return
//     */
//    @Override
//    public MultiLineChartDataVo getTrendByEnergy(MonitoringEnergy monitoringEnergy) {
//        CommentUtil.resetCompanyIdIfNull(monitoringEnergy);
//        List<MonitoringEnergy> resultList = monitoringEnergyMapper.getTrendByEnergy(monitoringEnergy);
//        // 提取所有日期并排序
//        List<Long> xAxis = resultList.stream()
//                .map(MonitoringEnergy::getRecordDay)
//                .distinct()
//                .sorted()
//                .collect(Collectors.toList());
//
//        // 按规格分组并处理数据
//        List<SeriesDataVo> yAxis = resultList.stream()
//                .collect(Collectors.groupingBy(MonitoringEnergy::getSteelSpec))
//                .entrySet().stream()
//                .map(entry -> {
//                    String steelSpec = entry.getKey();
//                    List<MonitoringEnergy> dailyUsages = entry.getValue();
//                    ArrayList<Double> data = new ArrayList<>(Collections.nCopies(xAxis.size(), 0.0));
//                    dailyUsages.forEach(usage -> {
//                        int index = xAxis.indexOf(usage.getRecordDay());
//                        if (index != -1) {
//                            data.set(index, usage.getEnergyUsage() != null ? usage.getEnergyUsage().doubleValue() : 0.0);
//                        }
//                    });
//                    SeriesDataVo seriesData = new SeriesDataVo();
//                    seriesData.setName(steelSpec);
//                    seriesData.setData(data);
//                    return seriesData;
//                })
//                .collect(Collectors.toList());
//
//        MultiLineChartDataVo multiLineChartData = new MultiLineChartDataVo();
//        multiLineChartData.setXAxis(xAxis);
//        multiLineChartData.setYAxis(yAxis);
//        return multiLineChartData;
//    }

}
